/**
 * 
 */
package sniper.targets;

import java.util.logging.Logger;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Publish data on http://pastebin.com/
 * 
 * @author Alessio Pace
 *
 */
public class PastebinTarget implements Target {
	
	private Logger log = Logger.getLogger(PastebinTarget.class.getCanonicalName());

	public static final String PASTEBIN_DOMAIN = "pastebin.com";
	public static final String POST_URL = "/pastebin.php";
	public static final String POSTER_PARAM_NAME = "poster";
	public static final String SNIPPET_PARAM_NAME = "code2";
	public static final String PASTE_PARAM_NAME = "paste";
	public static final String PASTE_PARAM_VALUE = "Send";
	
	private String domain;
	

	
	/**
	 * @param domainPrefix the prefix before <tt>pastebin.com/</tt>, such as <tt>sniper.pastebin.com</tt>.
	 *
	 */
	public PastebinTarget(String domainPrefix){
		
		if(domainPrefix != null && domainPrefix.length() > 0){
			this.domain = "http://" + domainPrefix + "." + PASTEBIN_DOMAIN;
		}
		else{
			this.domain = "http://" + PASTEBIN_DOMAIN;
		}
		
		
	}
	
	
	
	public String getDomain() {
		return domain;
	}


	public void submit(String snippet) throws Exception {
		
		final HttpClient httpClient = new HttpClient();
		
		final PostMethod postMethod = new PostMethod(this.domain + POST_URL);
		//postMethod.setFollowRedirects(true);
		
		
		postMethod.setParameter("format", "text");
		
		postMethod.setParameter(POSTER_PARAM_NAME, "sniper");
		
		postMethod.setParameter(SNIPPET_PARAM_NAME, snippet);
		
		postMethod.setParameter(PASTE_PARAM_NAME, PASTE_PARAM_VALUE);
		
	
		postMethod.setParameter("expiry", "d");
		
		log.info("Submitting to: " + postMethod.getURI());
		
		int statusCode = httpClient.executeMethod(postMethod);
		
		postMethod.releaseConnection();
		
		log.info("Released connection");
		
		String location = postMethod.getResponseHeader("Location").getValue();
		
		
		
		log.info("Status code: " + statusCode);
		log.info("Location: " + location);
		
		
	}

}
